#include <iostream>
#include <algorithm>
#include <string>
#include <cstdio>
#include <vector>
#include <stack>
#include <queue>
#include <set>
using namespace std;
struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};

class Solution
{
public:
    ListNode *removeElements(ListNode *head, int val)
    {
        while (head && head->val == val)
        {
            head = head->next;
        }
        ListNode *pre = NULL, *ptr = head;
        while (ptr != nullptr)
        {
            if (ptr->val == val)
            {
                pre->next = ptr->next;
                ptr = pre;
            }
            pre = ptr;
            ptr = ptr->next;
        }
        return head;
    }
};